嗨,我是 A Fei,大家週末過得如何?五倍振興券想好怎麼花了嗎?如果沒有,可以給我(被揍),啊不是,也可以考慮捐給弱勢團體唷,這也是我最近才知道的,原來振興券不只可以消費,也可以捐助。
閒聊完後,馬上讓我們看看今天的題目:
(題目來源:Codewars)
Write a function that takes an array of strings as an argument and returns a sorted array containing the same strings, ordered from shortest to longest.
For example, if this array were passed as an argument:
["Telescopes", "Glasses", "Eyes", "Monocles"]
Your function would return the following array:
["Eyes", "Glasses", "Monocles", "Telescopes"]
All of the strings in the array passed to your function will be different lengths, so you will not have to decide how to order multiple strings of the same length.
題目要我們把一陣列中的字串(元素),依照長度依序排好,我馬上想到 sort 方法,這邊可以介紹一下 sort 的進階用法,一般 sort 是昇序排列,那如果要降序呢?你可以在 sort 後面接上 block,寫法是 array.sort {|a, b| b <=> a }
,<=> 運算子將在 a 小於 b 時回傳負數,當 a 大於 b 時回傳正數,當 a 和 b 相等時回傳 0,藉此兩兩比較、排序陣列中的元素。讓我們直接試試:
a = ["a", "b", "c", "d", "e"]
a.sort {|a, b| b <=> a }
# => ["e", "d", "c", "b", "a"]
同樣的道理,反過來寫的話就是昇序,以下為我的解答:
def sort_by_length(arr)
arr.sort {|a, b| a.length <=> b.length }
end
對比評分最高的答案:
def sort_by_length(arr)
arr.sort_by(&:length)
end
它更加準確地用了 sort_by 方法,sort_by 後面可以接上要排序的條件,例如官網的例子:
%w{apple pear fig}.sort_by { |word| word.length }
#=> ["fig", "pear", "apple"]
而 &: 在上一章提過,這算是一種縮寫法。
好啦,今天的解題紀錄就到這,大家掰掰~